import dayjs from 'dayjs'
import { appConfig } from '@/config/app'

export default {
  prefixOssUrl (val) {
    return appConfig.staticUrl + val
  },
  timeFormat (d, f = 'YYYY-MM-DD HH:mm') {
    if (!d) {
      return '1999-01-01 00:00'
    }
    return dayjs(d).format(f)
  },
  amountFormat (number, decimals = 2, decPoint, thousandsSep = ",") {
    number = (number + '').replace(/[^0-9+-Ee.]/g, '')
    const n = !isFinite(+number) ? 0 : +number
    const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
    const sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
    const dec = (typeof decPoint === 'undefined') ? '.' : decPoint
    let s = ''
    const toFixedFix = function (n, prec) {
      const k = Math.pow(10, prec)
      return '' + Math.ceil(n * k) / k
    }

    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
    const re = /(-?\d+)(\d{3})/
    while (re.test(s[0])) {
      s[0] = s[0].replace(re, '$1' + sep + '$2')
    }

    if ((s[1] || '').length < prec) {
      s[1] = s[1] || ''
      s[1] += new Array(prec - s[1].length + 1).join('0')
    }
    return s.join(dec)
  },
  getVal (s, k) {
    if (s instanceof Object) {
      return $_.get(s, k) || '--'
    }
    return s || '--'
  },
  isObjHasBlank (obj, skipAttr = []) {
    for (let i in obj) {
      if (!obj[i] && !skipAttr.includes(i)) {
        return true
      }
    }
  },
  getYear (d) {
    return dayjs(d).year()
  },
  getMonth (d) {
    return dayjs(d).month() + 1
  },
  getDayjsObj (v) {
    return dayjs(v)
  },
  getServerExceptionMsg (s) {
    if (!s) {
      return '服务端错误~'
    } else {
      const mk = s.split('BizException: ')
      return mk.length === 2 ? mk[1] : '服务端错误~'
    }
  }
}